package tgc.edu.exam.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpSession;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import tgc.edu.exam.entity.SysUser;
import tgc.edu.exam.entity.User;
import tgc.edu.exam.form.UserForm;
import tgc.edu.exam.security.UserUtils;
import tgc.edu.exam.service.BookRecordService;
import tgc.edu.exam.service.MenuService;
import tgc.edu.exam.service.SysRoleService;
import tgc.edu.exam.service.SysUserService;
import tgc.edu.exam.service.UserService;
import tgc.edu.exam.custom.AjaxResult;
import tgc.edu.exam.entity.BookRecord;
import tgc.edu.exam.entity.Menu;
import tgc.edu.exam.entity.SysRole;

@Controller
public class LoginController {
	@Autowired
	private SysUserService userService;
	@Autowired
	private SysRoleService roleService;
	@Autowired
	private UserUtils userUtils;
	@Autowired
	private MenuService menuService;
	@Autowired
	private UserService modelService;
	@Autowired
	private BookRecordService recordService;

	@RequestMapping(value = { "/login", "/" }, method = RequestMethod.GET)
	public String login(ModelMap map) {
		return "main/login";
	}
	@RequestMapping("/index")
	public String index() {
		return "main/index";
	}

	@RequestMapping(value = "/main")
	public String main(ModelMap map,HttpSession session) {
		SysUser user = userUtils.getUser();
		Set<String> role = AuthorityUtils.authorityListToSet(SecurityContextHolder.getContext().getAuthentication().getAuthorities());
		if(role.contains("ROLE_USER")) {
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String date = df.format(new Date());
			Boolean f = true;
			Date dqDate;
			try {
				dqDate = df.parse(date);
				List<BookRecord> reader = recordService.findByUsername(user.getUsername());
				for (BookRecord r : reader) {
					Date endDate = df.parse(r.getReturnData());
					if(endDate.before(dqDate)&&r.getState().equals("已借")){
						f = false;
						break;
					}
				}
			} catch (ParseException e) {
				e.printStackTrace();
			}
			if(f){
				session.removeAttribute("time");
				return "main/welcome";
			}else{
				System.out.println("违约了");
				session.setAttribute("time", "您违约了还书日期，账号已被封，请尽快联系管理员！");
				return "redirect:login";
			}
		}
		List<Menu> menus = menuService.findAllMenu();
		System.out.println("菜单："+menus.toString());
		map.put("menus", menus);
		return "main/main";
	}
	/**
	 * 首页
	 * @return
	 */
	@RequestMapping("/manage")
	public String manage() {
		return "main/manage";
	}
	/**
	 * 注册
	 * @return
	 */
	@RequestMapping("/register")
	public String register() {
		return "main/register";
	}
	@RequestMapping("/saveuser")
	public String saveuser(UserForm form) {
		User model = new User();
		SysRole role = roleService.findByCode("ROLE_USER");
		model.getRole().add(role);
		BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
		BeanUtils.copyProperties(form, model);
		model.setPassword(encoder.encode("123456"));
		modelService.save(model);
		return "main/login";
	}
	/**
	 * 修改密码
	 * @param oldPwd
	 * @param newPwd
	 * @return
	 */
	@RequestMapping(value="/changepwd")
	@ResponseBody
	public Object changepwd(String oldPwd,String newPwd) {
		BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
		SysUser user = userUtils.getUser();
		String password = user.getPassword();
		if(!encoder.matches(oldPwd, password)) {
			return new AjaxResult(false, "原密码不正确！");
		}
		user.setPassword(encoder.encode(newPwd));
		userService.save(user);
		return new AjaxResult(true,"密码修改成功");
		
	}
	
}
